class ChessAI {
    constructor(depth = 10) {
        this.maxDepth = depth;
        // 棋子基础价值
        this.pieceValues = {
            '将': 10000, '帅': 10000,
            '车': 900,
            '马': 400,
            '炮': 450,
            '象': 200, '相': 200,
            '士': 200, '仕': 200,
            '卒': 100, '兵': 100
        };
        // 位置价值表（示例）
        this.positionValues = {
            '卒': this.generatePawnPositionValues(),
            '兵': this.generatePawnPositionValues(),
            // 其他棋子的位置价值表
        };
        
        // 添加调试信息计数器
        this.evaluatedPositions = 0;
        this.searchDepth = 0;
    }

    // 生成兵卒的位置价值表
    generatePawnPositionValues() {
        const values = new Array(10).fill(0).map(() => new Array(9).fill(0));
        for (let y = 0; y < 10; y++) {
            for (let x = 0; x < 9; x++) {
                if (y >= 5) {
                    values[y][x] = 50; // 过河的兵价值更高
                }
                if (x >= 3 && x <= 5) {
                    values[y][x] += 10; // 中心控制加分
                }
            }
        }
        return values;
    }

    // 获取所有可能的移动
    getPossibleMoves(board, color) {
        const moves = [];
        board.pieces.forEach(piece => {
            if (piece.color === color) {
                for (let x = 0; x < 9; x++) {
                    for (let y = 0; y < 10; y++) {
                        if (board.isValidMove(piece, x, y)) {
                            moves.push({
                                piece: piece,
                                targetX: x,
                                targetY: y
                            });
                        }
                    }
                }
            }
        });
        return moves;
    }

    // 评估局面分数
    evaluateBoard(board) {
        this.evaluatedPositions++;
        let score = 0;
        
        board.pieces.forEach(piece => {
            const baseValue = this.pieceValues[piece.type];
            const positionValue = this.positionValues[piece.type]?.[piece.y]?.[piece.x] || 0;
            const totalValue = baseValue + positionValue;
            score += piece.color === 'black' ? totalValue : -totalValue;
        });

        return score;
    }

    // Minimax算法 + Alpha-Beta剪枝
    minimax(board, depth, alpha, beta, isMaximizing) {
        if (depth === 0) {
            return this.evaluateBoard(board);
        }

        const moves = this.getPossibleMoves(board, isMaximizing ? 'black' : 'red');
        
        // 检查是否有将/帅被吃掉
        const hasKing = board.pieces.some(p => p.type === '将');
        const hasGeneral = board.pieces.some(p => p.type === '帅');
        if (!hasKing) return Infinity;  // 黑方胜
        if (!hasGeneral) return -Infinity;  // 红方胜

        let bestValue = isMaximizing ? -Infinity : Infinity;

        for (const move of moves) {
            // 模拟移动
            const originalPiece = board.pieces.find(p => 
                p.x === move.targetX && p.y === move.targetY);
            const originalX = move.piece.x;
            const originalY = move.piece.y;
            
            // 执行移动
            if (originalPiece) {
                board.pieces = board.pieces.filter(p => p !== originalPiece);
            }
            move.piece.x = move.targetX;
            move.piece.y = move.targetY;

            const evalScore = this.minimax(board, depth - 1, alpha, beta, !isMaximizing);
            
            // 恢复移动
            move.piece.x = originalX;
            move.piece.y = originalY;
            if (originalPiece) {
                board.pieces.push(originalPiece);
            }

            if (isMaximizing) {
                bestValue = Math.max(bestValue, evalScore);
                alpha = Math.max(alpha, evalScore);
            } else {
                bestValue = Math.min(bestValue, evalScore);
                beta = Math.min(beta, evalScore);
            }

            if (beta <= alpha) {
                break; // Alpha-Beta剪枝
            }
        }

        return bestValue;
    }

    // 获取最佳移动
    getBestMove(board) {
        // 重置计数器
        this.evaluatedPositions = 0;
        this.searchStartTime = Date.now();
        
        let bestMove = null;
        let bestValue = -Infinity;
        const moves = this.getPossibleMoves(board, 'black');
        
        console.log(`开始思考，共有 ${moves.length} 个可能的移动...`);

        for (const move of moves) {
            // 模拟移动
            const originalPiece = board.pieces.find(p => 
                p.x === move.targetX && p.y === move.targetY);
            const originalX = move.piece.x;
            const originalY = move.piece.y;
            
            // 执行移动
            if (originalPiece) {
                board.pieces = board.pieces.filter(p => p !== originalPiece);
            }
            move.piece.x = move.targetX;
            move.piece.y = move.targetY;

            const moveValue = this.minimax(board, this.maxDepth - 1, -Infinity, Infinity, false);
            
            // 恢复移动
            move.piece.x = originalX;
            move.piece.y = originalY;
            if (originalPiece) {
                board.pieces.push(originalPiece);
            }

            console.log(`评估移动: ${move.piece.type} 从(${originalX},${originalY})到(${move.targetX},${move.targetY}), 评分: ${moveValue}`);

            if (moveValue > bestValue) {
                bestValue = moveValue;
                bestMove = move;
            }
        }

        const timeSpent = (Date.now() - this.searchStartTime) / 1000;
        console.log(`
思考完成:
- 评估局面数: ${this.evaluatedPositions}
- 思考时间: ${timeSpent.toFixed(2)}秒
- 每秒评估局面: ${Math.round(this.evaluatedPositions / timeSpent)}
- 最佳移动: ${bestMove.piece.type} 从(${bestMove.piece.x},${bestMove.piece.y})到(${bestMove.targetX},${bestMove.targetY})
- 最佳评分: ${bestValue}
        `);

        return bestMove;
    }
}